package com.crazymaker.springcloud.base.security.handler;

import com.alibaba.fastjson.JSON;
import com.crazymaker.springcloud.common.result.RestOut;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class AuthFailureHandler implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
        response.setHeader("Content-Type", "text/html;charset=UTF-8");
        response.setStatus(HttpStatus.UNAUTHORIZED.value());

        RestOut<Object> error = RestOut.error(e.getMessage());
        response.getWriter().write(JSON.toJSONString(error));
    }
}
